package core

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

type Config struct {
	mqsPath string `json:"mqspath"`
	Env             string `json:"env"`
	LogPath         string `json:"logpath"`
}

func (c *Config) init(filePath string) error {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		log.Fatalln("Failed to load configuration.", err)
		return err
	}

	if err := json.Unmarshal([]byte(data), &c); err != nil {
		log.Fatalln("Failed to parse configuration JSON: %v", err)
		return err
	}

	if strings.ToLower(c.Env) == "prod" {
		logFile, err := os.OpenFile(c.LogPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
		if err != nil {
			log.Fatalln("Failed to create log output file with err: %v", err)
			return err
		}
		log.SetOutput(logFile)
	}

	return nil
}
